#include <iostream>
#include <thread>

#include "TaskPool.h"

TaskPool::TaskPool(int32_t bufferSize)
    : m_bufferSize(bufferSize)
    , m_mutex(std::make_shared<std::mutex>())
    , m_condition(std::make_shared<std::condition_variable>())
{

}

void TaskPool::append(std::shared_ptr<AbstractTask> task)
{
    std::unique_lock<std::mutex> lock(*m_mutex);
    while (m_taskPool.size() == m_bufferSize)
    {
        m_condition->wait(lock);
    }
    std::cout << "append: " << std::this_thread::get_id() << std::endl;

    m_taskPool.push(task);
    m_condition->notify_all();
}

std::shared_ptr<AbstractTask> TaskPool::takeFirst()
{
    std::unique_lock<std::mutex> lock(*m_mutex);
    while (m_taskPool.empty())
    {
        m_condition->wait(lock);
    }

    std::cout << "takeFirst: " << std::this_thread::get_id() << std::endl;
    std::shared_ptr<AbstractTask> task = m_taskPool.front();
    m_taskPool.pop();
    m_condition->notify_all();

    return task;
}

bool TaskPool::empty() const
{
    std::unique_lock<std::mutex> lock(*m_mutex);
    return m_taskPool.empty();
}


